package moltencore.game;

import moltencore.config.Config;
import org.apache.log4j.Logger;

import java.util.Collection;
import java.util.LinkedList;

public class GameShootEmUp extends Game {
	private static Logger logger = Logger.getLogger(GameShootEmUp.class);

	public GameShootEmUp(long hostIdentification) {
		super(hostIdentification);
	}

	@Override
	protected void reflectOnFieldUpdate(Field field) {
		if(field.isBusted()) {
			loserFields.add(field);
		}
		else if(isFieldEmpty(field)) {
			winnerFields.add(field);
		}
	}

	private boolean isFieldEmpty(Field field) {
		return field.getGridBubbleCount() == 0 && field.getMovingBubbleCount() == 0;
	}

	/**
	 * Handle the end of the game if it is over.
	 */
	@Override
	protected void handlePossibleGameEnd() {
		// the game has ended if we have a winner
		if(winnerFields.size() == 1) {
			// if a field is not yet a loser field and not in the winners list either add it to the loser fields list
			for(Field field : fields) {
				if(!winnerFields.contains(field) && !loserFields.contains(field)) {
					loserFields.add(field);
				}
			}
			setState(State.Ended);
		}
		// the game has ended if every field but one has lost
		else if(loserFields.size() == fields.size() - 1) {
			// find the one winner field
			for(Field field : this.getFields()) {
				if(!loserFields.contains(field)) {
					winnerFields.add(field);
				}
			}
			setState(State.Ended);
		}
		if(getState() == State.Ended) {
			notifyListenersGameEnded(winnerFields, loserFields);
		}
	}
}